package com.ruoyi.bill.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.basicsystem.domain.ZnSupplier;
import com.ruoyi.basicsystem.service.IZnDepotService;
import com.ruoyi.basicsystem.service.IZnSupplierService;
import com.ruoyi.bill.domain.*;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.material.domain.ZnMaterialExtend;
import com.ruoyi.material.domain.ZnUnit;
import com.ruoyi.material.service.IZnMaterialService;
import com.ruoyi.material.service.IZnUnitService;
import com.ruoyi.system.domain.ZnMaterialProperty;
import com.ruoyi.system.domain.ZnProfitDetail;
import com.ruoyi.system.domain.ZnProfitHistory;
import com.ruoyi.system.service.IZnMaterialPropertyService;
import com.ruoyi.system.service.IZnProfitDetailService;
import com.ruoyi.system.service.IZnProfitHistoryService;
import com.ruoyi.system.service.impl.ProfitTask;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bill.service.IZnDepotHeadService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 单据管理
 *
 * @date 2022-02-19
 */
@RestController
@RequestMapping("/bill/retail")
public class ZnDepotHeadController extends BaseController
{
    @Autowired
    private IZnDepotHeadService znDepotHeadService;
    @Autowired
    private IZnMaterialPropertyService znMaterialPropertyService;
    @Autowired
    private IZnDepotService znDepotService;
    @Autowired
    private IZnMaterialService znMaterialService;
    @Autowired
    private IZnSupplierService znSupplierService;
    @Autowired
    private IZnUnitService znUnitService;
    @Autowired
    private IZnProfitHistoryService znProfitHistoryService;
    @Autowired
    private IZnProfitDetailService znProfitDetailService;

    /**
     * 利润统计计算(先进先出），只计算采购和销售
     *      * 截止到目前为止，按自然月进行逐月进行统计，并且统计月份内的销售出库都必须是已出库状态。
     */
    @PreAuthorize("@ss.hasPermi('system:profithistory:compute')")
    @GetMapping(value = "/computeProfit")
    public AjaxResult computeProfit()
    {

        ZnProfitHistory znProfitHistory = new ZnProfitHistory();
        znProfitHistory.setTenantId(SecurityUtils.getTenantId());
        znProfitHistory.setState(0);
        Integer state = znProfitHistoryService.selectZnProfitHistoryCount(znProfitHistory);
        if(state == 0){
            znProfitHistory.setCreateBy(SecurityUtils.getUsername());
            znProfitHistory.setCreateTime(new Date());
            znProfitHistoryService.insertZnProfitHistory(znProfitHistory);

            ZnDepotHead queryParam = new ZnDepotHead();
            queryParam.setTenantId(SecurityUtils.getTenantId());
            queryParam.setDeleteFlag("0");
            queryParam.setType("出库");
            queryParam.setSubType("销售");
            Calendar cal = Calendar.getInstance();
//            queryParam.getParams().put("endOperTime",DateUtils.getTime());
            queryParam.getParams().put("endOperTime","2022-06-30 23:59:59");
            queryParam.getParams().put("status","2");//
            ZnProfitDetail znProfitDetail = new ZnProfitDetail();
            znProfitDetail.setTenantId(SecurityUtils.getTenantId());
            Map<String,Object> map = znProfitDetailService.findLastOperTimeAndInId(znProfitDetail);
            if(map!=null){
                if(map.containsKey("out_oper_time")){
                    if(map.get("out_oper_time") !=null){
                        queryParam.getParams().put("beginOperTime", map.get("out_oper_time"));
                    }
                }
            }
            //判断销售单是否有未出库
            int saleCount = znDepotHeadService.selectZnDepotHeadCount(queryParam);
            if(saleCount>0){
                return AjaxResult.error("有未确认出库的销售出库单，请先确定已出库后，在进行计算");
            }
            //判断采购单是否有未审核
            queryParam.setType("入库");
//            queryParam.setSubType("采购");
            queryParam.getParams().put("status","2");//不等于
            queryParam.getParams().put("subType","其它");//不等于

            int purchaseCount = znDepotHeadService.selectZnDepotHeadCount(queryParam);
            if(purchaseCount>0){
                return AjaxResult.error("有未确定入库的（包括采购入库、报溢单、其它入库）单，请先确定入库后，在进行计算");
            }
            //起一个任务
//            ProfitTask worker = new ProfitTask(znProfitDetailService,znDepotHeadMapper,znProfitDetailMapper,znProfitHistoryMapper,znMaterialInitialStockService,queryParam, znProfitHistory.getId(),SecurityUtils.getTenantId());
            ProfitTask worker = new ProfitTask(znProfitDetailService,znProfitHistory.getId(),SecurityUtils.getTenantId());
            worker.start();
        }else{
            return AjaxResult.error("当前正在盘点计算中，请稍后查看盘点结果！");
        }
        return AjaxResult.success("开始盘点计算中，请稍后查看盘点结果！");
    }
    /**
     * 查询欠款单据管理列表
     */
//    @PreAuthorize("@ss.hasAnyPermi('bill:retail:list,bill:retailreturns:list,bill:purchaseorder:list')")
    @GetMapping("/listDebt")
    public TableDataInfo listDebt(ZnDepotHead znDepotHead)
    {

        if(znDepotHead.getParams().containsKey("ids")){
            Object ids = znDepotHead.getParams().get("ids");
            if(StringUtils.isNotEmpty(ids.toString())){
                Long[] ints = new Long[ids.toString().split(",").length];

                for(int i=0;i<ids.toString().split(",").length;i++){

                    ints[i] = Long.parseLong(ids.toString().split(",")[i]);
                }
                znDepotHead.getParams().put("ids", ints);
            }
        }
        znDepotHead.setDeleteFlag("0");
        startPage();
        List<ZnDepotHead> list = znDepotHeadService.selectZnDepotHeadDebtList(znDepotHead);
        return getDataTable(list);
    }
    /**
     * 查询单据管理列表
     */
//    @PreAuthorize("@ss.hasAnyPermi('bill:retail:list,bill:retailreturns:list,bill:purchaseorder:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZnDepotHead znDepotHead)
    {
        startPage();
        znDepotHead.setTenantId(SecurityUtils.getTenantId());
        znDepotHead.setDeleteFlag("0");
        if(!znDepotHead.getParams().isEmpty()){
            if(znDepotHead.getParams().containsKey("beginOperTime")){
                znDepotHead.getParams().put("beginOperTime" ,znDepotHead.getParams().get("beginOperTime").toString()+" 00:00:00");
            }
            if(znDepotHead.getParams().containsKey("endOperTime")){
                znDepotHead.getParams().put("endOperTime" ,znDepotHead.getParams().get("endOperTime").toString()+" 23:59:59");
            }
        }
        List<ZnDepotHead> list = znDepotHeadService.selectZnDepotHeadList(znDepotHead);
        return getDataTable(list);
    }

    /**
     * 导出单据商品列表
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:export,bill:retailreturns:export')")
    @Log(title = "单据管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOrderDetail")
    public void exportOrderDetail(HttpServletResponse response, ZnDepotHead znDepotHead)
    {
        znDepotHeadService.exportOrder(response,znDepotHead);
    }
    /**
     * 导出单据商品列表
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:export,bill:retailreturns:export')")
    @Log(title = "单据管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOrderTotal")
    public void exportOrderTotal(HttpServletResponse response, ZnDepotHead znDepotHead)
    {
        znDepotHeadService.exportOrder(response,znDepotHead);
    }
    /**
     * 导出单据管理列表
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:export,bill:retailreturns:export')")
    @Log(title = "单据管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZnDepotHead znDepotHead)
    {
        List<ZnDepotHead> list = znDepotHeadService.selectZnDepotHeadList(znDepotHead);
        ExcelUtil<ZnDepotHead> util = new ExcelUtil<ZnDepotHead>(ZnDepotHead.class);
        util.exportExcel(response, list, "单据管理数据");
    }

    /**
     * 获取单据管理详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:query,bill:retail:copy,bill:retailreturns:copy')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ZnDepotHead znDepotHead = znDepotHeadService.selectZnDepotHeadById(id);
        System.out.println(JSON.toJSONString(znDepotHead));
        return AjaxResult.success(znDepotHead);
    }

    /**
     * 新增单据管理
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:add,bill:retailreturns:add')")
    @Log(title = "单据管理", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody ZnDepotHead znDepotHead)
    {
        System.out.println(JSON.toJSONString(znDepotHead));
        return toAjax(znDepotHeadService.insertZnDepotHead(znDepotHead));
    }

    /**
     * 修改单据管理
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:edit,bill:retailreturns:edit')")
    @Log(title = "单据管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody ZnDepotHead znDepotHead)
    {
        System.out.println(JSON.toJSONString(znDepotHead));
        return toAjax(znDepotHeadService.updateZnDepotHead(znDepotHead));
    }

    /**
     * 删除单据管理
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:retail:remove,bill:retailreturns:remove')")
    @Log(title = "单据管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int rows = znDepotHeadService.deleteZnDepotHeadByIds(ids);
        if(rows < ids.length){
            return AjaxResult.success("单据删除操作成功,部分单据已审核而无法删除");
        }else if(rows ==0){//抱歉，只有未审核的单据才能审核
            return AjaxResult.error("抱歉，只有未审核的单据才能删除");
        }else{
            return AjaxResult.success("单据删除成功");
        }
    }

    /**
     * 获取单据编号
     * @param  type 1 零售(0出库[LSCK]、1退货[LSTH]) 2销售（0订单[SSDD] 1出库[SSCK] 2退货[SSTH]） 3 采购（0订单[CGDD] 1出库[CGCK] 2退货[CGTH]） 5其它（0入库[QTRK] 1出库[QTCK] 2调拨出库[DBCK] 3组装单[ZZDD] 4拆卸单[CXDD]） 为文字拼音的首字母
     * @author nexiaozi
     * @date 2022年2月20日
     */
    @GetMapping(value = "/getBillNo/{type}")
    public AjaxResult getBillNo(@PathVariable("type") String type)
    {
        return AjaxResult.success("单据编号生成成功",znDepotHeadService.getBillNo(type.trim()));
    }
    /**
     * 修改单据信息状态
     * @param status 状态 1 审核 0 反审核
     * @param ids 单据主键
     * @author nexiaozi
     * @date 2022年2月20日
     *
     */
    @PreAuthorize("@ss.hasAnyPermi('bill:depotbyrk:ined,bill:depotqtrk:ined,bill:retail:check,bill:retail:unCheck,bill:retailreturns:check,bill:retailreturns:unCheck,bill:saleorder:check,bill:saleorder:unCheck,bill:saleout:check,bill:saleout:unCheck,bill:saleout:outed,bill:saleoutreturns:check,bill:saleoutreturns:unCheck,bill:purchaseorder:check,bill:purchaseorder:unCheck,bill:purchasein:check,bill:purchasein:unCheck,bill:purchasein:ined,bill:purchaseinreturns:check,bill:purchaseinreturns:unCheck,bill:depotqtrk:check,bill:depotqtrk:unCheck,bill:depotqtck:check,bill:depotqtck:unCheck,bill:depotdbck:check,bill:depotdbck:unCheck,bill:depotzzdd:check,bill:depotzzdd:unCheck,bill:depotcxdd:check,bill:depotcxdd:unCheck,bill:depotbsck:check,bill:depotbsck:unCheck,bill:depotbyrk:check,bill:depotbyrk:unCheck')")
    @Log(title = "单据管理", businessType = BusinessType.UPDATE)
    @GetMapping("/{status}/{ids}")
    public AjaxResult changeStatus(@PathVariable("status") String status,@PathVariable("ids") Long[] ids )
    {
        int rows = znDepotHeadService.changeStatus(ids,status);
//        if(rows < ids.length){
//            return AjaxResult.error("单据" + (status.equals("1")?"审核":"反审核") + (rows >0?"成功":"失败")+(ids.length>0?",有部分单据":"")+"已"+(status.equals("1")?"审核":"反审核"));
//        }else if(rows ==0){//抱歉，只有未审核的单据才能审核
//            return AjaxResult.error("抱歉，只有"+(status.equals("1")?"未审核":"已审核")+"的单据才能" + (status.equals("1")?"审核":"反审核"));
//        }else{
//            return AjaxResult.success("单据" + (status.equals("1")?"审核":"反审核") + "成功");
//        }

        if(rows ==0){//抱歉，只有未审核的单据才能审核
            return AjaxResult.error("抱歉，只有"+(status.equals("1")?"未审核":"已审核")+"的单据才能" + (status.equals("1")?"审核":(status.equals("0")?"反审核":"出/入库")));
        }else{
            if(rows < ids.length){
                return AjaxResult.error("单据" + (status.equals("1")?"审核":(status.equals("0")?"反审核":"出/入库")) + "成功,有部分单据已"+(status.equals("1")?"审核":"已反审核或者已出/入库"));
            }else{
                return AjaxResult.success("单据" + (status.equals("1")?"审核":(status.equals("0")?"反审核":"出/入库")) + "成功");
            }
        }
    }
    /**
     * 只根据商品id查询单据列表 库存流水
     * @param mId
     * @param request
     * @return
     */
    @GetMapping(value = "/findDetailByTypeAndMaterialId")
    public AjaxResult findDetailByTypeAndMaterialId(
            @RequestParam("materialId") String mId, HttpServletRequest request)throws Exception {
        startPage();
        Map<String, String> parameterMap =new HashMap<>();
        parameterMap.put("mId", mId);
        parameterMap.put("billNo", request.getParameter("billNo"));
        String queryParam_type =  request.getParameter("type");
        if (StringUtils.isNotEmpty(queryParam_type) && queryParam_type.contains("@")) {
            parameterMap.put("type", queryParam_type.split("@")[0]);
            parameterMap.put("subType", queryParam_type.split("@")[1]);
        }

        parameterMap.put("beginOperTime", request.getParameter("beginOperTime"));
        parameterMap.put("endOperTime", request.getParameter("endOperTime"));
        Map<String, Object> objectMap = new HashMap<String, Object>();

        List<DepotItemVo4DetailByTypeAndMId> list = znDepotHeadService.findDetailByTypeAndMaterialIdList(parameterMap);
        JSONArray dataArray = new JSONArray();
        if (list != null) {
            for (DepotItemVo4DetailByTypeAndMId d: list) {
                JSONObject item = new JSONObject();
                item.put("number", d.getNumber()); //编号
                item.put("barCode", d.getBarCode()); //条码
                item.put("materialName", d.getMaterialName()); //名称
                String type = d.getType();
                String subType_ = d.getSubType();
                if(("其它").equals(type)) {
                    item.put("type", subType_); //进出类型
                } else {
                    item.put("type", subType_ + type); //进出类型
                }
                item.put("depotName", d.getDepotName()); //仓库名称
                item.put("basicNumber", d.getBnum()); //数量
                item.put("operTime", DateUtils.getCenternTime(d.getOtime())); //时间
                item.put("materialUnit", d.getMaterialUnit()); //产品单位
                dataArray.add(item);
            }
        }
        if (list == null) {
            objectMap.put("rows", new ArrayList<Object>());
            objectMap.put("total",0);
            return AjaxResult.success(objectMap);
        }
        objectMap.put("rows", dataArray);
        Long total=new PageInfo(list).getTotal();
        objectMap.put("total", total);
          return AjaxResult.success(objectMap);
    }
    /**
     * 进货统计/采购统计
     * @param monthTime
     * @param materialParam
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('report:purchase:list')")
    @GetMapping(value = "/buyIn")
    public AjaxResult buyIn(
                                  @RequestParam("monthTime") String monthTime,
                                  @RequestParam("materialParam") String materialParam,
                                  HttpServletRequest request)throws Exception {
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime) && !monthTime.equals("Invalid date")){
            endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
            startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
        }
            List<DepotItemVo4WithInfoEx> dataList = znDepotHeadService.selectZnDepotHeadPage("入库",StringUtil.toNull(materialParam),
                    startTime, endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> list = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
            //int total = depotItemService.findByAllCount(StringUtil.toNull(materialParam), endTime);
            Long total=new PageInfo(dataList).getTotal();
        res.put("total",total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    BigDecimal InSum = znDepotHeadService.buyOrSale("入库", "采购", diEx.getMId(),diEx.getMeId(), monthTime, "number");
                    BigDecimal OutSum = znDepotHeadService.buyOrSale("出库", "采购退货", diEx.getMId(),diEx.getMeId(), monthTime, "number");
                    BigDecimal InSumPrice = znDepotHeadService.buyOrSale("入库", "采购", diEx.getMId(),diEx.getMeId(), monthTime, "price");
                    BigDecimal OutSumPrice = znDepotHeadService.buyOrSale("出库", "采购退货", diEx.getMId(),diEx.getMeId(), monthTime, "price");
                    BigDecimal InOutSumPrice = InSumPrice.subtract(OutSumPrice);
                    item.put("barCode", diEx.getBarCode());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(list, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
                    item.put("materialUnit", diEx.getMaterialUnit());
                    item.put("unitName", diEx.getUnitName());
                    item.put("inSum", InSum);
                    item.put("outSum", OutSum);
                    item.put("inSumPrice", InSumPrice);
                    item.put("outSumPrice", OutSumPrice);
                    item.put("inOutSumPrice",InOutSumPrice);//实际采购金额
                    dataArray.add(item);
                }
            }
        res.put("data",dataArray);
        return res;
    }
    /**
     * 销售统计

     * @param monthTime
     * @param materialParam
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('report:sale:list')")
    @GetMapping(value = "/saleOut")
    public AjaxResult saleOut(
                                    @RequestParam("monthTime") String monthTime,
                                    @RequestParam("materialParam") String materialParam,
                                    HttpServletRequest request)throws Exception {
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime)){
             endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
             startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
        }
            List<DepotItemVo4WithInfoEx> dataList =  znDepotHeadService.selectZnDepotHeadPage("出库",StringUtil.toNull(materialParam),
                    startTime, endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> list = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
            //String[] mpArr = mpList.split(",");
            Long total=new PageInfo(dataList).getTotal();
        res.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    BigDecimal OutSumRetail = znDepotHeadService.buyOrSale("出库", "零售", diEx.getMId(), diEx.getMeId(), monthTime,"number");
                    BigDecimal OutSum = znDepotHeadService.buyOrSale("出库", "销售", diEx.getMId(), diEx.getMeId(), monthTime,"number");
                    BigDecimal InSumRetail = znDepotHeadService.buyOrSale("入库", "零售退货", diEx.getMId(), diEx.getMeId(), monthTime,"number");
                    BigDecimal InSum = znDepotHeadService.buyOrSale("入库", "销售退货", diEx.getMId(), diEx.getMeId(), monthTime,"number");
                    BigDecimal OutSumRetailPrice = znDepotHeadService.buyOrSale("出库", "零售", diEx.getMId(), diEx.getMeId(), monthTime,"price");
                    BigDecimal OutSumPrice = znDepotHeadService.buyOrSale("出库", "销售", diEx.getMId(), diEx.getMeId(), monthTime,"price");
                    BigDecimal InSumRetailPrice = znDepotHeadService.buyOrSale("入库", "零售退货", diEx.getMId(), diEx.getMeId(), monthTime,"price");
                    BigDecimal InSumPrice = znDepotHeadService.buyOrSale("入库", "销售退货", diEx.getMId(), diEx.getMeId(), monthTime,"price");
                    BigDecimal OutInSumPrice = (OutSumRetailPrice.add(OutSumPrice)).subtract(InSumRetailPrice.add(InSumPrice));
                    item.put("barCode", diEx.getBarCode());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(list, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
                    item.put("materialUnit", diEx.getMaterialUnit());
                    item.put("unitName", diEx.getUnitName());
                    item.put("outSum", OutSumRetail.add(OutSum));
                    item.put("inSum", InSumRetail.add(InSum));
                    item.put("outSumPrice", OutSumRetailPrice.add(OutSumPrice));
                    item.put("inSumPrice", InSumRetailPrice.add(InSumPrice));
                    item.put("outInSumPrice",OutInSumPrice);//实际销售金额
                    dataArray.add(item);
                }
            }
        res.put("data",dataArray);
        return res;
    }
    /**
     * 获取扩展信息
     *list
     * @return
     */
    public String getOtherInfo(List<ZnMaterialProperty> mpArr, DepotItemVo4WithInfoEx diEx)throws Exception {
        String materialOther = "";
        for (int i = 0; i < mpArr.size(); i++) {
            if (mpArr.get(i).getNativeName().equals("制造商")) {
                materialOther = materialOther + ((diEx.getMMfrs() == null || diEx.getMMfrs().equals("")) ? "" : "(" + diEx.getMMfrs() + ")");
            }
            if (mpArr.get(i).getNativeName().equals("自定义1")) {
                materialOther = materialOther + ((diEx.getMOtherField1() == null || diEx.getMOtherField1().equals("")) ? "" : "(" + diEx.getMOtherField1() + ")");
            }
            if (mpArr.get(i).getNativeName().equals("自定义2")) {
                materialOther = materialOther + ((diEx.getMOtherField2() == null || diEx.getMOtherField2().equals("")) ? "" : "(" + diEx.getMOtherField2() + ")");
            }
            if (mpArr.get(i).getNativeName().equals("自定义3")) {
                materialOther = materialOther + ((diEx.getMOtherField3() == null || diEx.getMOtherField3().equals("")) ? "" : "(" + diEx.getMOtherField3() + ")");
            }
        }
        return materialOther;
    }

    /**
     * 获取扩展信息
     * 数组
     * @return
     */
    public String getOtherInfo(String[] mpArr, DepotItemVo4WithInfoEx diEx)throws Exception {
        String materialOther = "";
        for (int i = 0; i < mpArr.length; i++) {
            if (mpArr[i].equals("制造商")) {
                materialOther = materialOther + ((diEx.getMMfrs() == null || diEx.getMMfrs().equals("")) ? "" : "(" + diEx.getMMfrs() + ")");
            }
            if (mpArr[i].equals("自定义1")) {
                materialOther = materialOther + ((diEx.getMOtherField1() == null || diEx.getMOtherField1().equals("")) ? "" : "(" + diEx.getMOtherField1() + ")");
            }
            if (mpArr[i].equals("自定义2")) {
                materialOther = materialOther + ((diEx.getMOtherField2() == null || diEx.getMOtherField2().equals("")) ? "" : "(" + diEx.getMOtherField2() + ")");
            }
            if (mpArr[i].equals("自定义3")) {
                materialOther = materialOther + ((diEx.getMOtherField3() == null || diEx.getMOtherField3().equals("")) ? "" : "(" + diEx.getMOtherField3() + ")");
            }
        }
        return materialOther;
    }

    /**
     * 入库出库明细接口

     * @param oId
     * @param number
     * @param materialParam
     * @param depotId
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('report:indetail:list,report:outdetail:list')")
    @GetMapping(value = "/findInDetail")
    public AjaxResult findInDetail(@RequestParam(value = "organId", required = false) Long oId,
                                         @RequestParam("number") String number,
                                         @RequestParam("materialParam") String materialParam,
                                         @RequestParam(value = "depotId", required = false) Long depotId,
                                         @RequestParam("beginTime") String beginTime,
                                         @RequestParam("endTime") String endTime,
                                         @RequestParam("type") String type,
                                         @RequestParam("status") String status,
                                         HttpServletRequest request)throws Exception {
            AjaxResult res = new AjaxResult();
            Map<String, Object> map = new HashMap<String, Object>();
            List<Long> depotList = new ArrayList<>();
            if(depotId != null) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getLong("id"));
                }
            }
            startPage();
            List<DepotHeadVo4InDetail> resList = new ArrayList<DepotHeadVo4InDetail>();
            beginTime = DateUtils.parseDayToTime(beginTime, DateUtils.DAY_FIRST_TIME);
            endTime = DateUtils.parseDayToTime(endTime,DateUtils.DAY_LAST_TIME);
            List<DepotHeadVo4InDetail> list = znDepotHeadService.findByAll(beginTime, endTime, type, materialParam, depotList, oId, number,status);
            Long total=new PageInfo(list).getTotal();
            res.put("total", total);
            //存放数据json数组
            if (null != list) {
                for (DepotHeadVo4InDetail dhd : list) {
                    resList.add(dhd);
                }
            }
        res.put("data", resList);

        return res;
    }


    /**
     * 调拨明细统计
     * @param number
     * @param materialParam
     * @param beginTime
     * @param endTime
     * @param subType
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasPermi('report:dbdetail:list')")
    @GetMapping(value = "/findAllocationDetail")
    public AjaxResult findallocationDetail(
                                                 @RequestParam("number") String number,
                                                 @RequestParam("materialParam") String materialParam,
                                                 @RequestParam(value = "depotId", required = false) Long depotIdIn,
                                                 @RequestParam(value = "depotIdF", required = false) Long depotIOut,
                                                 @RequestParam("beginTime") String beginTime,
                                                 @RequestParam("endTime") String endTime,
                                                 @RequestParam("subType") String subType,
                                                 HttpServletRequest request)throws Exception {
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
            List<Long> depotList = new ArrayList<>();
            List<Long> depotFList = new ArrayList<>();
            if(depotIdIn != null) {
                depotList.add(depotIdIn);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getLong("id"));
                }
            }
            if(depotIOut != null) {
                depotFList.add(depotIOut);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotFList.add(object.getLong("id"));
                }
            }
            beginTime = DateUtils.parseDayToTime(beginTime, DateUtils.DAY_FIRST_TIME);
            endTime = DateUtils.parseDayToTime(endTime,DateUtils.DAY_LAST_TIME);
            List<DepotHeadVo4InDetail> list = znDepotHeadService.findAllocationDetail(beginTime, endTime, subType, number, materialParam, depotList, depotFList);
            Long total=new PageInfo(list).getTotal();
            res.put("total", total);
        res.put("data", list);

        return res;
    }

    /**
     * 入库出库统计接口

     * @param oId
     * @param materialParam
     * @param depotId
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('report:intotal:list,report:outtotal:list')")
    @GetMapping(value = "/findInOutMaterialCount")
    public AjaxResult findInOutMaterialCount(
                                                   @RequestParam(value = "organId", required = false) Long oId,
                                                   @RequestParam("materialParam") String materialParam,
                                                   @RequestParam(value = "depotId", required = false) Long depotId,
                                                   @RequestParam("beginTime") String beginTime,
                                                   @RequestParam("endTime") String endTime,
                                                   @RequestParam("type") String type,
                                                   HttpServletRequest request)throws Exception {
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
            List<Long> depotList = new ArrayList<>();
            if(depotId != null) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr =  znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getLong("id"));
                }
            }
            List<DepotHeadVo4InOutMCount> resList = new ArrayList<>();
            beginTime = DateUtils.parseDayToTime(beginTime,DateUtils.DAY_FIRST_TIME);
            endTime = DateUtils.parseDayToTime(endTime,DateUtils.DAY_LAST_TIME);
            startPage();
            List<DepotHeadVo4InOutMCount> list = znDepotHeadService.findInOutMaterialCount(beginTime, endTime, type, materialParam, depotList, oId);
        Long total=new PageInfo(list).getTotal();
        res.put("total", total);
            //存放数据json数组
            if (null != list) {
                for (DepotHeadVo4InOutMCount dhc : list) {
                    resList.add(dhc);
                }
            }
        res.put("data", resList);

        return res;
    }


    /**
     * 查找进销存所有的明细

     * @param depotIds
     * @param monthTime
     * @param materialParam
     * @param request
     * @return
     * @throws Exception
     */
    @PreAuthorize("@ss.hasPermi('report:inouttotal:list')")
    @GetMapping(value = "/findInOutStockReport")
    public AjaxResult findInOutStockReport(
                                      @RequestParam("depotIds") String depotIds,
                                      @RequestParam("monthTime") String monthTime,
                                      @RequestParam("materialParam") String materialParam,
                                     /* @RequestParam("mpList") String mpList,*/
                                      HttpServletRequest request)throws Exception {

        if(StringUtil.isEmpty(depotIds)) {
          return AjaxResult.error("请选择仓库");
        }
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<>();
//            String timeA = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
//            String timeB = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime)){
            endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
            startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
        }
            List<Long> depotList = StringUtil.strToLongList(depotIds);
            List<DepotItemVo4WithInfoEx> dataList = znDepotHeadService.findInOutStockReport(StringUtil.toNull(materialParam),
                    endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> mpList = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
            Long total=new PageInfo(dataList).getTotal();
        res.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                List<Long> idList = new ArrayList<>();
                for (DepotItemVo4WithInfoEx m : dataList) {
                    idList.add(m.getMId());
                }
                List<ZnMaterialExtend> meList = znMaterialService.getListByMIds(idList);
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    Long mId = diEx.getMId();
                    item.put("barCode", diEx.getBarCode());
                    item.put("materialName", diEx.getMName());
                    item.put("materialModel", diEx.getMModel());
                    item.put("materialStandard", diEx.getMStandard());
                    //扩展信息
                    String materialOther = getOtherInfo(mpList, diEx);
                    item.put("materialOther", materialOther);
                    item.put("materialColor", diEx.getMColor());
//                    item.put("unitName", (StringUtils.isNotEmpty(diEx.getUnitName())?diEx.getUnitName():diEx.getMaterialUnit()));
                    item.put("unitName", diEx.getMaterialUnit());
                    BigDecimal prevSum = znDepotHeadService.getStockByParamWithDepotList(depotList,mId,null,startTime);
                    Map<String,BigDecimal> intervalMap = znDepotHeadService.getIntervalMapByParamWithDepotList(depotList,mId,startTime,endTime);
                    BigDecimal inSum = intervalMap.get("inSum");
                    BigDecimal outSum = intervalMap.get("outSum");
                    BigDecimal thisSum = prevSum.add(inSum).subtract(outSum);
                    item.put("prevSum", prevSum);
                    item.put("inSum", inSum);
                    item.put("outSum", outSum);
                    item.put("thisSum", thisSum);
                    for(ZnMaterialExtend me:meList) {
                        if(me.getMaterialId().longValue() == diEx.getMId().longValue()) {
                            if(me.getPurchaseDecimal()!=null) {
                                item.put("unitPrice", me.getPurchaseDecimal());
                                item.put("thisAllPrice", thisSum.multiply(me.getPurchaseDecimal()));
                            }
                        }
                    }
                    dataArray.add(item);
                }
            }
        res.put("data", dataArray);
        return res;
    }
    /**查找进销存所有的明细
     * 统计总计金额
     * @param depotIds
     * @param monthTime
     * @param materialParam
     * @param request
     * @return
     */
    @GetMapping(value = "/findInOutStockReportTotalCountMoney")
    public AjaxResult findInOutStockReportTotalCountMoney(@RequestParam("depotIds") String depotIds,
                                            @RequestParam("monthTime") String monthTime,
                                            @RequestParam("materialParam") String materialParam,
                                            HttpServletRequest request) throws Exception{

        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<>();
            String endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
            List<Long> depotList = StringUtil.strToLongList(depotIds);
            List<DepotItemVo4WithInfoEx> dataList = znDepotHeadService.findInOutStockReport(StringUtil.toNull(materialParam),
                    endTime);
            BigDecimal thisAllPrice = BigDecimal.ZERO;
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    Long mId = diEx.getMId();
                    BigDecimal thisSum = znDepotHeadService.getStockByParamWithDepotList(depotList,mId,null,endTime);
                    BigDecimal unitPrice = diEx.getPurchaseDecimal();
                    if(unitPrice == null) {
                        unitPrice = BigDecimal.ZERO;
                    }
                    thisAllPrice = thisAllPrice.add(thisSum.multiply(unitPrice));
                }
            }
        res.put("totalCount", thisAllPrice);

        return res;
    }
    /**
     * 对账单接口

     * @param beginTime
     * @param endTime
     * @param organId
     * @param supType
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('report:customer:list,report:supply:list')")
    @GetMapping(value = "/findStatementAccount")
    public AjaxResult findStatementAccount(
                                                 @RequestParam("beginTime") String beginTime,
                                                 @RequestParam("endTime") String endTime,
                                                 @RequestParam(value = "organId", required = false) Long organId,
                                                 @RequestParam("supType") String supType,
                                                 HttpServletRequest request) throws Exception{
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
            beginTime = DateUtils.parseDayToTime(beginTime,DateUtils.DAY_FIRST_TIME);
            endTime = DateUtils.parseDayToTime(endTime,DateUtils.DAY_LAST_TIME);
            List<DepotHeadVo4StatementAccount> list = znDepotHeadService.findStatementAccount(beginTime, endTime, organId, supType);
            Long total=new PageInfo(list).getTotal();
            map.put("rows", list);
            map.put("total", total);
            if(null!=organId) {
                ZnSupplier supplier = znSupplierService.selectZnSupplierById(organId);
                BigDecimal beginNeed = BigDecimal.ZERO;
                if (("客户").equals(supType)) {
                    if(supplier.getBeginNeedGet()!=null) {
                        beginNeed = supplier.getBeginNeedGet();
                    }
                } else if (("供应商").equals(supType)) {
                    if(supplier.getBeginNeedPay()!=null) {
                        beginNeed = supplier.getBeginNeedPay();
                    }
                }
                BigDecimal firstMoney = znDepotHeadService.findTotalPay(organId, beginTime, supType)
                        .subtract(znDepotHeadService.findTotalPay(organId, beginTime, supType)).add(beginNeed);
                BigDecimal lastMoney = znDepotHeadService.findTotalPay(organId, endTime, supType)
                        .subtract(znDepotHeadService.findTotalPay(organId, endTime, supType)).add(beginNeed);
                map.put("firstMoney", firstMoney); //期初
                map.put("lastMoney", lastMoney);  //期末
            }
        res.put("data",map);
        return res;
    }
    /**
     * 库存预警报表
     * @return
     */
    @PreAuthorize("@ss.hasPermi('report:stockwarning:list')")
    @GetMapping(value = "/findStockWarningCount")
    public AjaxResult findStockWarningCount(
                                                  @RequestParam("materialParam") String materialParam,
                                                  @RequestParam(value = "depotId", required = false) Long depotId
                                                 )throws Exception {
        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
            List<Long> depotList = new ArrayList<>();
            if(depotId != null) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getLong("id"));
                }
            }
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> mpList = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
            List<DepotItemStockWarningCount> list = znDepotHeadService.findStockWarningCount( materialParam, depotList);
            //存放数据json数组
            if (null != list) {
                for (DepotItemStockWarningCount disw : list) {
                    DepotItemVo4WithInfoEx diEx = new DepotItemVo4WithInfoEx();
                    diEx.setMMfrs(disw.getMMfrs());
                    diEx.setMOtherField1(disw.getMOtherField1());
                    diEx.setMOtherField2(disw.getMOtherField2());
                    diEx.setMOtherField3(disw.getMOtherField3());
                    disw.setMaterialOther(getOtherInfo(mpList, diEx));
                    disw.setMaterialUnit(getUName(disw.getMaterialUnit(), disw.getUnitName()));
                    if(disw.getCurrentNumber().compareTo(disw.getLowSafeStock())<0) {
                        disw.setLowCritical(disw.getLowSafeStock().subtract(disw.getCurrentNumber()));
                        disw.setHighCritical(BigDecimal.ZERO);
                    }
                    if(disw.getCurrentNumber().compareTo(disw.getHighSafeStock())>0) {
                        disw.setLowCritical(BigDecimal.ZERO);
                        disw.setHighCritical(disw.getCurrentNumber().subtract(disw.getHighSafeStock()));
                    }
                }
            }
        Long total=new PageInfo(list).getTotal();
            map.put("total", total);
            map.put("rows", list);
        res.put("data",map);
        return res;
    }

    /**
     * 获取单位
     * @param materialUnit
     * @param uName
     * @return
     */
    public String getUName(String materialUnit, String uName) {
        String unitName = null;
        if(StringUtil.isNotEmpty(materialUnit)) {
            unitName = materialUnit;
        } else if(StringUtil.isNotEmpty(uName)) {
            unitName = uName;
        }
        return unitName;
    }

    /**
     * 通过主表Id查询附表信息集合
     */
//    @PreAuthorize("@ss.hasAnyPermi('bill:retail:query,bill:retail:copy,bill:retailreturns:copy')")
    @GetMapping(value = "/getItems/{id}")
    public AjaxResult getItems(@PathVariable("id") Long id)
    {
        return AjaxResult.success(znDepotHeadService.selectZnDepotItemByHeadId(id));
    }


    /**
     * 根据编号查询进出库等单据信息
     * @param number
     * @param request
     * @return
     */
    @GetMapping(value = "/getDetailByNumber")
    public AjaxResult getDetailByNumber(@RequestParam("number") String number,
                                              HttpServletRequest request)throws Exception {
        AjaxResult res = new AjaxResult();
        DepotHeadVo4List dhl = new DepotHeadVo4List();
            List<DepotHeadVo4List> list = znDepotHeadService.getDetailByNumber(number);
            if(list.size() == 1) {
                dhl = list.get(0);
            }
        res.put("data",dhl);
        return res;
    }
    /**
     * 单据明细列表
     * @param headerId
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getDetailList")
    public AjaxResult getDetailList(@RequestParam("headerId") Long headerId,
                                          HttpServletRequest request)throws Exception {
        AjaxResult res = new AjaxResult();
            List<DepotItemVo4WithInfoEx> dataList = new ArrayList<DepotItemVo4WithInfoEx>();
            if(headerId != 0) {
                dataList = znDepotHeadService.getDetailList(headerId);
            }
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> mpList = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("materialId", diEx.getMaterialId());
                    item.put("materialExtendId", diEx.getMaterialExtendId() == null ? "" : diEx.getMaterialExtendId());
                    item.put("barCode", diEx.getBarCode());
                    item.put("name", diEx.getMName());
                    item.put("standard", diEx.getMStandard());
                    item.put("model", diEx.getMModel());
                    item.put("color", diEx.getMColor());
                    item.put("materialOther", getOtherInfo(mpList, diEx));
                    BigDecimal stock;
                    if(StringUtil.isNotEmpty(diEx.getSku())){
                        stock = znDepotHeadService.getSkuStockByParam(diEx.getDepotId(),diEx.getMaterialExtendId(),null,null);
                    } else {
                        stock = znDepotHeadService.getStockByParam(diEx.getDepotId(),diEx.getMaterialId(),null,null);
                        ZnUnit unitInfo = znMaterialService.findUnit(diEx.getMaterialId()); //查询计量单位信息
                        if (StringUtil.isNotEmpty(unitInfo.getName())) {
                            String materialUnit = diEx.getMaterialUnit();
                            stock = znUnitService.parseStockByUnit(stock, unitInfo, materialUnit);
                        }
                    }
                    DecimalFormat df = new DecimalFormat("0.00#");
                    if(!Objects.nonNull(stock)){
                        stock=BigDecimal.ZERO;
                    }
                    stock = stock.setScale(2,BigDecimal.ROUND_HALF_UP);
                    item.put("stock",stock);
                    item.put("unit", diEx.getMaterialUnit());
                    item.put("snList", diEx.getSnList());
                    item.put("batchNumber", diEx.getBatchNumber());
                    item.put("expirationDate", DateUtils.parseDateToStr(diEx.getExpirationDate()));
                    item.put("sku", diEx.getSku());
                    item.put("enableSerialNumber", diEx.getEnableSerialNumber());
                    item.put("enableBatchNumber", diEx.getEnableBatchNumber());
                    if(!Objects.nonNull(diEx.getOperNumber())){
                        diEx.setOperNumber(BigDecimal.ZERO);
                    }
                    diEx.setOperNumber(diEx.getOperNumber().setScale(2,BigDecimal.ROUND_HALF_UP));
                    item.put("operNumber", diEx.getOperNumber());
                    if(!Objects.nonNull(diEx.getBasicNumber())){
                        diEx.setBasicNumber(BigDecimal.ZERO);
                    }
                    diEx.setBasicNumber(diEx.getBasicNumber().setScale(2,BigDecimal.ROUND_HALF_UP));
                    item.put("basicNumber", diEx.getBasicNumber());
                    item.put("preNumber", diEx.getOperNumber()); //原数量
                    BigDecimal finishNumber = znDepotHeadService.getFinishNumber(diEx.getMaterialId(), diEx.getHeaderId());
                    if(!Objects.nonNull(diEx.getBasicNumber())){
                        finishNumber = BigDecimal.ZERO;
                    }
                    item.put("finishNumber", finishNumber.setScale(2,BigDecimal.ROUND_HALF_UP)); //已入库|已出库
                    if(!Objects.nonNull(diEx.getUnitPrice())){
                        diEx.setUnitPrice(BigDecimal.ZERO);
                    }
                    BigDecimal unitPrice =diEx.getUnitPrice().setScale(2,BigDecimal.ROUND_HALF_UP);
                    String getUnitPrice = df.format(unitPrice);
                    item.put("unitPrice", getUnitPrice);
                    if(!Objects.nonNull(diEx.getTaxUnitPrice())){
                        diEx.setTaxUnitPrice(BigDecimal.ZERO);
                    }
                    BigDecimal taxUnitPrice =diEx.getTaxUnitPrice().setScale(2,BigDecimal.ROUND_HALF_UP);
                    String getTaxUnitPrice = df.format(taxUnitPrice);
                    item.put("taxUnitPrice", getTaxUnitPrice);
                    if(!Objects.nonNull(diEx.getAllPrice())){
                        diEx.setAllPrice(BigDecimal.ZERO);
                    }
                    BigDecimal allPrice =diEx.getAllPrice().setScale(2,BigDecimal.ROUND_HALF_UP);
                    String getAllPrice = df.format(allPrice);
                    item.put("allPrice", getAllPrice);
                    item.put("remark", diEx.getRemark());
                    item.put("depotId", diEx.getDepotId() == null ? "" : diEx.getDepotId());
                    item.put("depotName", diEx.getDepotId() == null ? "" : diEx.getDepotName());
                    item.put("anotherDepotId", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotId());
                    item.put("anotherDepotName", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotName());
                    if(!Objects.nonNull(diEx.getTaxRate())){
                        diEx.setTaxRate(BigDecimal.ZERO);
                    }
                    item.put("taxRate", diEx.getTaxRate().setScale(2,BigDecimal.ROUND_HALF_UP));
                    if(!Objects.nonNull(diEx.getTaxMoney())){
                        diEx.setTaxMoney(BigDecimal.ZERO);
                    }
                    BigDecimal taxMoney =diEx.getTaxMoney().setScale(2,BigDecimal.ROUND_HALF_UP);
                    String getTaxMoney = df.format(taxMoney);
                    item.put("taxMoney", getTaxMoney);
                    if(!Objects.nonNull(diEx.getTaxLastMoney())){
                        diEx.setTaxLastMoney(BigDecimal.ZERO);
                    }
                    BigDecimal taxLastMoney =diEx.getTaxLastMoney().setScale(2,BigDecimal.ROUND_HALF_UP);
                    String getTaxLastMoney = df.format(taxLastMoney);
                    item.put("taxLastMoney", getTaxLastMoney);
                    item.put("mType", diEx.getMaterialType());
                    item.put("op", 1);
                    dataArray.add(item);
                }
            }
        res.put("data", dataArray);
        return res;
    }
    /**
     * 导出销售订单新增模板
     */
    @Log(title = "订单商品导入模板", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response, ZnDepotItemImportTemplate znDepotItemExportTemplate)
    {
        ExcelUtil<ZnDepotItemImportTemplate> util = new ExcelUtil<ZnDepotItemImportTemplate>(ZnDepotItemImportTemplate.class);
        util.exportExcel(response, new ArrayList<>(), "订单商品");
    }
    /**
     * 订单商品导入
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "订单商品导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importMaterialData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Date startDate = new Date();
        String startStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",startDate);
        logger.debug("开始导入数据！");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String operName = loginUser.getUsername();
        ExcelUtil<ZnDepotItemImportTemplate> util = new ExcelUtil<ZnDepotItemImportTemplate>(ZnDepotItemImportTemplate.class);
        List<ZnDepotItemImportTemplate> list = util.importExcel(file.getInputStream());
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            return AjaxResult.error("导入数据不能为空！");
        }
        logger.debug("导入数据："+list.size());
        AjaxResult j = znMaterialService.analysisMaterialList(list);
//        String message = znMaterialService.importMaterial(file, updateSupport, operName);
        logger.debug("结束导入数据！");
        Date endDate = new Date();
        String endStr =  DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",endDate);
        logger.debug("开始时间："+startStr +",结束时间：" + endStr);
        logger.debug("用时："+(endDate.getTime()-startDate.getTime()));
        logger.debug("用时："+(endDate.getTime()-startDate.getTime())/1000+"s");
        return j;
    }
    /**
     * 导出库存预警
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出库存预警", businessType = BusinessType.EXPORT)
    @PostMapping("/stockWarningExport")
    public void stockWarningExport(HttpServletResponse response, ExportParam exportParam)
    {
        Long depotId = exportParam.getDepotId();
        String materialParam = exportParam.getMaterialParam();
//        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Long> depotList = new ArrayList<>();
        if(depotId != null) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getLong("id"));
            }
        }
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> mpList = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
        List<DepotItemStockWarningCount> list = znDepotHeadService.findStockWarningCount( materialParam, depotList);
        //存放数据json数组
        if (null != list) {
            for (DepotItemStockWarningCount disw : list) {
                DepotItemVo4WithInfoEx diEx = new DepotItemVo4WithInfoEx();
                diEx.setMMfrs(disw.getMMfrs());
                diEx.setMOtherField1(disw.getMOtherField1());
                diEx.setMOtherField2(disw.getMOtherField2());
                diEx.setMOtherField3(disw.getMOtherField3());
                try {
                    disw.setMaterialOther(getOtherInfo(mpList, diEx));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                disw.setMaterialUnit(getUName(disw.getMaterialUnit(), disw.getUnitName()));
                if(disw.getCurrentNumber().compareTo(disw.getLowSafeStock())<0) {
                    disw.setLowCritical(disw.getLowSafeStock().subtract(disw.getCurrentNumber()));
                    disw.setHighCritical(BigDecimal.ZERO);
                }
                if(disw.getCurrentNumber().compareTo(disw.getHighSafeStock())>0) {
                    disw.setLowCritical(BigDecimal.ZERO);
                    disw.setHighCritical(disw.getCurrentNumber().subtract(disw.getHighSafeStock()));
                }
            }
        }

        ExcelUtil<DepotItemStockWarningCount> util = new ExcelUtil<DepotItemStockWarningCount>(DepotItemStockWarningCount.class);
        util.exportExcel(response, list, "库存预警");
    }
    /**
     * 导出进销存统计
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出进销存统计", businessType = BusinessType.EXPORT)
    @PostMapping("/inOutStockReportExport")
    public void inOutStockReportExport(HttpServletResponse response, ExportParam exportParam)
    {
//        startPage();
        String depotIds = exportParam.getDepotIds();
        String monthTime = exportParam.getMonthTime();
        String materialParam = exportParam.getMaterialParam();
        if(StringUtil.isEmpty(depotIds)) {
            throw new RuntimeException("请选择仓库");
        }
        Map<String, Object> map = new HashMap<>();
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime)){
            try {
                endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
                startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<Long> depotList = StringUtil.strToLongList(depotIds);
        List<DepotItemVo4WithInfoEx> dataList = znDepotHeadService.findInOutStockReport(StringUtil.toNull(materialParam),
                endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> mpList = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
        List<ERPReportExport> result = new ArrayList<>();
        //存放数据json数组
        if (null != dataList) {
            List<Long> idList = new ArrayList<>();
            for (DepotItemVo4WithInfoEx m : dataList) {
                idList.add(m.getMId());
            }
            List<ZnMaterialExtend> meList = znMaterialService.getListByMIds(idList);
            for (DepotItemVo4WithInfoEx diEx : dataList) {
                ERPReportExport item = new ERPReportExport();
                Long mId = diEx.getMId();
                item.setBarCode( diEx.getBarCode());
                item.setMaterialName( diEx.getMName());
                item.setMaterialModel( diEx.getMModel());
                item.setMaterialStandard( diEx.getMStandard());
                //扩展信息
                String materialOther = null;
                try {
                    materialOther = getOtherInfo(mpList, diEx);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                item.setMaterialOther( materialOther);
                item.setUnitName( diEx.getMaterialUnit());
                BigDecimal prevSum = znDepotHeadService.getStockByParamWithDepotList(depotList,mId,null,startTime);
                Map<String,BigDecimal> intervalMap = znDepotHeadService.getIntervalMapByParamWithDepotList(depotList,mId,startTime,endTime);
                BigDecimal inSum = intervalMap.get("inSum");
                BigDecimal outSum = intervalMap.get("outSum");
                BigDecimal thisSum = prevSum.add(inSum).subtract(outSum);
                item.setPrevSum(prevSum);
                item.setInSum(inSum);
                item.setOutSum(outSum);
                item.setThisSum(thisSum);
                for(ZnMaterialExtend me:meList) {
                    if(me.getMaterialId().longValue() == diEx.getMId().longValue()) {
                        if(me.getPurchaseDecimal()!=null) {
                            item.setUnitPrice( me.getPurchaseDecimal());
                            item.setThisAllPrice(thisSum.multiply(me.getPurchaseDecimal()));
                        }else{
                            item.setUnitPrice( BigDecimal.ZERO);
                            item.setThisAllPrice(BigDecimal.ZERO);
                        }
                    }
                }
                result.add(item);
            }
        }
        ExcelUtil<ERPReportExport> util = new ExcelUtil<ERPReportExport>(ERPReportExport.class);
        util.exportExcel(response, result, "进销存统计");
    }
    /**
     * 导出入库、出库汇总
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出入库、出库汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/inOutMaterialCountExport")
    public void inOutMaterialCountExport(HttpServletResponse response, ExportParam exportParam)
    {
        Long depotId = exportParam.getDepotId();
        String type = exportParam.getType();
        String status = exportParam.getStatus();
        Long oId = exportParam.getOrganId();
        String materialParam = exportParam.getMaterialParam();
        String number = exportParam.getNumber();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Long> depotList = new ArrayList<>();
        if(depotId != null) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr =  znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getLong("id"));
            }
        }
//        startPage();
        List<DepotHeadVo4InOutMCount> resList = new ArrayList<>();
        String beginTime = DateUtils.parseDayToTime(exportParam.getBeginTime(),DateUtils.DAY_FIRST_TIME);
        String endTime = DateUtils.parseDayToTime(exportParam.getEndTime(),DateUtils.DAY_LAST_TIME);
        List<DepotHeadVo4InOutMCount> list = znDepotHeadService.findInOutMaterialCount(beginTime, endTime, type, materialParam, depotList, oId);

        ExcelUtil<DepotHeadVo4InOutMCount> util = new ExcelUtil<DepotHeadVo4InOutMCount>(DepotHeadVo4InOutMCount.class);
        util.exportExcel(response, list, type+"汇总");
    }
    /**
     * 导出入库明细
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出入库明细", businessType = BusinessType.EXPORT)
    @PostMapping("/inDetailExport")
    public void inDetailExport(HttpServletResponse response, ExportParam exportParam)
    {
        Long depotId = exportParam.getDepotId();
        String type = exportParam.getType();
        String status = exportParam.getStatus();
        Long oId = exportParam.getOrganId();
        String materialParam = exportParam.getMaterialParam();
        String number = exportParam.getNumber();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Long> depotList = new ArrayList<>();
        if(depotId != null) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getLong("id"));
            }
        }
//        startPage();
        List<DepotHeadVo4InDetail> resList = new ArrayList<DepotHeadVo4InDetail>();
        String beginTime = DateUtils.parseDayToTime(exportParam.getBeginTime(), DateUtils.DAY_FIRST_TIME);
        String endTime = DateUtils.parseDayToTime(exportParam.getEndTime(),DateUtils.DAY_LAST_TIME);
        List<DepotHeadVo4InDetail> list = znDepotHeadService.findByAll(beginTime, endTime, type, materialParam, depotList, oId, number,status);
        List<InDetailExport> result =  new ArrayList<>();
        for (DepotHeadVo4InDetail temp:list) {
            InDetailExport inDetailExport = new InDetailExport();
            BeanUtils.copyProperties(temp,inDetailExport);
            result.add(inDetailExport);
        }
        ExcelUtil<InDetailExport> util = new ExcelUtil<InDetailExport>(InDetailExport.class);
        util.exportExcel(response, result, "明细");
    }
    /**
     * 导出客户对账
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出客户对账", businessType = BusinessType.EXPORT)
    @PostMapping("/statementAccountExport")
    public void statementAccountExport(HttpServletResponse response, ExportParam exportParam)
    {
        Long organId = exportParam.getOrganId();
        String supType = exportParam.getSupType();
//        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String beginTime = DateUtils.parseDayToTime(exportParam.getBeginTime(),DateUtils.DAY_FIRST_TIME);
        String endTime = DateUtils.parseDayToTime(exportParam.getEndTime(),DateUtils.DAY_LAST_TIME);
        List<DepotHeadVo4StatementAccount> list = znDepotHeadService.findStatementAccount(beginTime, endTime, organId, supType);

        ExcelUtil<DepotHeadVo4StatementAccount> util = new ExcelUtil<DepotHeadVo4StatementAccount>(DepotHeadVo4StatementAccount.class);
        util.exportExcel(response, list, "客户对账");
    }
    /**
     * 导出销售统计
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出销售统计", businessType = BusinessType.EXPORT)
    @PostMapping("/saleOutExport")
    public void saleOutExport(HttpServletResponse response, ExportParam exportParam)
    {
        String  monthTime =  exportParam.getMonthTime();
        String  materialParam =  exportParam.getMaterialParam();
//        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime) && !monthTime.equals("Invalid date")){
            try {
                endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
                startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DepotItemVo4WithInfoEx> dataList =  znDepotHeadService.selectZnDepotHeadPage("出库",StringUtil.toNull(materialParam),
                startTime, endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> list = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
        List<DepotItemVoSaleOutEx> result = new ArrayList<>();
        if (null != dataList) {
            for (DepotItemVo4WithInfoEx diEx : dataList) {
                DepotItemVoSaleOutEx item = new DepotItemVoSaleOutEx();
                BigDecimal OutSumRetail = znDepotHeadService.buyOrSale("出库", "零售", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"number");
                BigDecimal OutSum = znDepotHeadService.buyOrSale("出库", "销售", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"number");
                BigDecimal InSumRetail = znDepotHeadService.buyOrSale("入库", "零售退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"number");
                BigDecimal InSum = znDepotHeadService.buyOrSale("入库", "销售退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"number");
                BigDecimal OutSumRetailPrice = znDepotHeadService.buyOrSale("出库", "零售", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"price");
                BigDecimal OutSumPrice = znDepotHeadService.buyOrSale("出库", "销售", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"price");
                BigDecimal InSumRetailPrice = znDepotHeadService.buyOrSale("入库", "零售退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"price");
                BigDecimal InSumPrice = znDepotHeadService.buyOrSale("入库", "销售退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime,"price");
                BigDecimal OutInSumPrice = (OutSumRetailPrice.add(OutSumPrice)).subtract(InSumRetailPrice.add(InSumPrice));
                item.setBarCode( diEx.getBarCode());
                item.setMaterialName(diEx.getMName());
                item.setMaterialModel( diEx.getMModel());
                item.setMaterialStandard(diEx.getMStandard());
                //扩展信息
                String materialOther = null;
                try {
                    materialOther = getOtherInfo(list, diEx);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                item.setMaterialOther(materialOther);
                item.setMaterialColor(diEx.getMColor());
                item.setMaterialUnit( diEx.getMaterialUnit());
                item.setUnitName( diEx.getUnitName());
                item.setInSum( InSum);
                item.setOutSum(OutSum);
                item.setInSumPrice( InSumPrice);
                item.setOutSumPrice(OutSumPrice);
                item.setInOutSumPrice(OutInSumPrice);//实际采购金额
                result.add(item);
            }
        }
        ExcelUtil<DepotItemVoSaleOutEx> util = new ExcelUtil<DepotItemVoSaleOutEx>(DepotItemVoSaleOutEx.class);
        util.exportExcel(response, result, "销售统计");
    }
    /**
     * 导出采购统计
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出采购统计", businessType = BusinessType.EXPORT)
    @PostMapping("/buyInExport")
    public void buyInExport(HttpServletResponse response, ExportParam exportParam)
    {
        String  monthTime =  exportParam.getMonthTime();
        String  materialParam =  exportParam.getMaterialParam();
//        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String endTime = null;
        String startTime = null;
        if(StringUtils.isNotEmpty(monthTime) && !monthTime.equals("Invalid date")){
            try {
                endTime = DateUtils.lastDayOfMonth(monthTime) + DateUtils.DAY_LAST_TIME;
                startTime = DateUtils.firstDayOfMonth(monthTime) + DateUtils.DAY_FIRST_TIME;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DepotItemVo4WithInfoEx> dataList = znDepotHeadService.selectZnDepotHeadPage("入库",StringUtil.toNull(materialParam),
                startTime, endTime);
        /**
         * 获取扩展信息
         */
        ZnMaterialProperty znMaterialProperty=new ZnMaterialProperty();
        znMaterialProperty.setEnabled(1);
        List<ZnMaterialProperty> list = znMaterialPropertyService.selectZnMaterialPropertyList(znMaterialProperty);
        List<DepotItemVoBuyInEx> result = new ArrayList<>();
        if (null != dataList) {
            for (DepotItemVo4WithInfoEx diEx : dataList) {
                DepotItemVoBuyInEx item = new DepotItemVoBuyInEx();
                BigDecimal InSum = znDepotHeadService.buyOrSale("入库", "采购", diEx.getMId(), diEx.getMaterialExtendId(), monthTime, "number");
                BigDecimal OutSum = znDepotHeadService.buyOrSale("出库", "采购退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime, "number");
                BigDecimal InSumPrice = znDepotHeadService.buyOrSale("入库", "采购", diEx.getMId(), diEx.getMaterialExtendId(), monthTime, "price");
                BigDecimal OutSumPrice = znDepotHeadService.buyOrSale("出库", "采购退货", diEx.getMId(), diEx.getMaterialExtendId(), monthTime, "price");
                BigDecimal InOutSumPrice = InSumPrice.subtract(OutSumPrice);
                item.setBarCode( diEx.getBarCode());
                item.setMaterialName(diEx.getMName());
                item.setMaterialModel( diEx.getMModel());
                item.setMaterialStandard(diEx.getMStandard());
                //扩展信息
                String materialOther = null;
                try {
                    materialOther = getOtherInfo(list, diEx);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                item.setMaterialOther(materialOther);
                item.setMaterialColor(diEx.getMColor());
                item.setMaterialUnit( diEx.getMaterialUnit());
                item.setUnitName( diEx.getUnitName());
                item.setInSum( InSum);
                item.setOutSum(OutSum);
                item.setInSumPrice( InSumPrice);
                item.setOutSumPrice(OutSumPrice);
                item.setInOutSumPrice(InOutSumPrice);//实际采购金额
                result.add(item);
            }
        }
        ExcelUtil<DepotItemVoBuyInEx> util = new ExcelUtil<DepotItemVoBuyInEx>(DepotItemVoBuyInEx.class);
        util.exportExcel(response, result, "采购统计");
    }
    /**
     * 导出调拨明细统计
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出调拨明细统计", businessType = BusinessType.EXPORT)
    @PostMapping("/allocationDetailExport")
    public void allocationDetailExport(HttpServletResponse response, ExportParam exportParam)
    {
//        startPage();
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Long> depotList = new ArrayList<>();
        List<Long> depotFList = new ArrayList<>();
        if(exportParam.getDepotIdIn() != null) {
            depotList.add(exportParam.getDepotIdIn());
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getLong("id"));
            }
        }
        if(exportParam.getDepotIOut() != null) {
            depotFList.add(exportParam.getDepotIOut());
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotFList.add(object.getLong("id"));
            }
        }
        String beginTime = DateUtils.parseDayToTime(exportParam.getBeginTime(), DateUtils.DAY_FIRST_TIME);
        String endTime = DateUtils.parseDayToTime(exportParam.getEndTime(),DateUtils.DAY_LAST_TIME);
        List<DepotHeadVo4InDetail> list = znDepotHeadService.findAllocationDetail(beginTime, endTime, exportParam.getSubType(), exportParam.getNumber(), exportParam.getMaterialParam(), depotList, depotFList);
        ExcelUtil<DepotHeadVo4InDetail> util = new ExcelUtil<DepotHeadVo4InDetail>(DepotHeadVo4InDetail.class);
        util.exportExcel(response, list, "调拨明细统计");
    }
    /**
     * 今天单据统计数据
     * @author nexiaozi
     * @date 2022年9月14日
     */
    @GetMapping(value = "/todayReport")
    public AjaxResult todayReport()
    {
        Map<String,Object> map = znDepotHeadService.selectReport(0);
        BigDecimal purchaserTotal = BigDecimal.ZERO;
        BigDecimal saleTotal = BigDecimal.ZERO;
        BigDecimal retailTotal = BigDecimal.ZERO;
        if(map !=null){
            purchaserTotal = new BigDecimal(map.get("purchaser_total").toString()).subtract(new BigDecimal(map.get("purchaser_return_total").toString()));
            saleTotal = new BigDecimal(map.get("sale_total").toString()).subtract(new BigDecimal(map.get("sale_return_total").toString()));
            retailTotal = new BigDecimal(map.get("retail_total").toString()).subtract(new BigDecimal(map.get("retail_return_total").toString()));
        }
        Map<String,BigDecimal> result = new HashMap<>();
        result.put("purchaserTodayTotal",purchaserTotal);
        result.put("saleTodayTotal",saleTotal);
        result.put("retailTodayTotal",retailTotal);
        return AjaxResult.success("今天单据统计数据查询成功",result);
    }
    /**
     * 本月单据统计数据
     * @author nexiaozi
     * @date 2022年9月14日
     */
    @GetMapping(value = "/monthReport")
    public AjaxResult monthReport()
    {
        Map<String,Object> map = znDepotHeadService.selectReport(1);
        BigDecimal purchaserTotal = BigDecimal.ZERO;
        BigDecimal saleTotal = BigDecimal.ZERO;
        BigDecimal retailTotal = BigDecimal.ZERO;
        if(map !=null){
//            purchaserTotal = new BigDecimal(map.get("purchaser_total").toString()).subtract(new BigDecimal(map.get("purchaser_return_total").toString()));
//            saleTotal = new BigDecimal(map.get("sale_total").toString()).subtract(new BigDecimal(map.get("sale_return_total").toString()));
//            retailTotal = new BigDecimal(map.get("retail_total").toString()).subtract(new BigDecimal(map.get("retail_return_total").toString()));
            purchaserTotal = new BigDecimal(map.get("purchaser_total").toString());
            saleTotal = new BigDecimal(map.get("sale_total").toString());
            retailTotal = new BigDecimal(map.get("retail_total").toString());
        }
        Map<String,BigDecimal> result = new HashMap<>();
        result.put("purchaserMonthTotal",purchaserTotal);
        result.put("saleMonthTotal",saleTotal);
        result.put("retailMonthTotal",retailTotal);
        return AjaxResult.success("本月单据统计数据查询成功",result);
    }
    /**
     * 近六个月单据统计数据
     * @author nexiaozi
     * @date 2022年9月14日
     */
    @GetMapping(value = "/lastSixMonthReport")
    public AjaxResult lastSixMonthReport()
    {

        Map<String,Object> result = new HashMap<>();
        List<Map<String,Object>> list = znDepotHeadService.selectLastSixMonthReport();
        BigDecimal purchaserTotal = BigDecimal.ZERO;
        BigDecimal saleTotal = BigDecimal.ZERO;
        BigDecimal retailTotal = BigDecimal.ZERO;
        List<String> months = DateUtils.getMonths(6);
        result.put("months",months);
        List<Map<String,Object>> purchaseList = new ArrayList<>();
        List<Map<String,Object>> purchaseReturnList = new ArrayList<>();
        List<Map<String,Object>> saleList = new ArrayList<>();
        List<Map<String,Object>> saleReturnList = new ArrayList<>();
        List<Map<String,Object>> retailList = new ArrayList<>();
        List<Map<String,Object>> retailReturnList = new ArrayList<>();

        List<BigDecimal> purchaseResultList = new ArrayList<>();
        List<BigDecimal> purchaseReturnResultList = new ArrayList<>();
        List<BigDecimal> saleResultList = new ArrayList<>();
        List<BigDecimal> saleReturnResultList = new ArrayList<>();
        List<BigDecimal> retailResultList = new ArrayList<>();
        List<BigDecimal> retailReturnResultList = new ArrayList<>();
        for (Map map:list) {
            if(map.get("sub_type").equals("采购")){
                purchaseList.add(map);
            }else  if(map.get("sub_type").equals("采购退货")){
                purchaseReturnList.add(map);
            }else  if(map.get("sub_type").equals("销售")){
                saleList.add(map);
            }else if(map.get("sub_type").equals("销售退货")){
                saleReturnList.add(map);
            }else  if(map.get("sub_type").equals("零售")){
                retailList.add(map);
            }else if(map.get("sub_type").equals("零售退货")){
                retailReturnList.add(map);
            }
        }
        if(!list.isEmpty()){
            BigDecimal zero = BigDecimal.ZERO;
            zero = zero.setScale(2,BigDecimal.ROUND_HALF_UP);
            for (String month:months) {
                if(purchaseList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:purchaseList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    purchaseResultList.add(val);
                }else{
                    purchaseResultList.add(zero);
                }
                if(purchaseReturnList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:purchaseReturnList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    purchaseReturnResultList.add(val);
                }else{
                    purchaseReturnResultList.add(zero);
                }

                if(saleList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:saleList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    saleResultList.add(val);
                }else{
                    saleResultList.add(zero);
                }
                if(saleReturnList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:saleReturnList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    saleReturnResultList.add(val);
                }else{
                    saleReturnResultList.add(zero);
                }

                if(retailList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:retailList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    retailResultList.add(val);
                }else{
                    retailResultList.add(zero);
                }
                if(retailReturnList.size()>0){
                    BigDecimal val = BigDecimal.ZERO;
                    for (Map<String,Object> map:retailReturnList) {
                        if(map.get("total_month").equals(month)){
                            val = new BigDecimal(map.get("total").toString());
                            continue;
                        }
                    }
                    val = val.setScale(2,BigDecimal.ROUND_HALF_UP);
                    retailReturnResultList.add(val);
                }else{
                    retailReturnResultList.add(zero);
                }
            }
        }
        result.put("purchaseData",purchaseResultList);
        result.put("purchaseReturnData",purchaseReturnResultList);
        result.put("saleData",saleResultList);
        result.put("saleReturnData",saleReturnResultList);
        result.put("retailData",retailResultList);
        result.put("retailReturnData",retailReturnResultList);
        System.out.println(JSON.toJSONString(result));
        return AjaxResult.success("近六个月单据统计数据查询成功",result);
    }

}
